package com.cnswhy.cloud.server.merchant.controller.spell;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.base.controller.SuperController;
import com.cnswhy.cloud.common.core.base.entity.SuperEntity;
import com.cnswhy.cloud.common.core.base.request.PageParams;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.mybatis.conditions.query.QueryWrap;
import com.cnswhy.cloud.common.core.utils.DateUtils;
import com.cnswhy.cloud.common.core.utils.SystemClockUtil;
import com.cnswhy.cloud.common.logging.uitls.MDCUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.mq.SpellDayendCancelMsg;
import com.cnswhy.cloud.server.common.entity.mq.SpellMsg;
import com.cnswhy.cloud.server.core.dto.ShopBrandPageDTO;
import com.cnswhy.cloud.server.core.dto.SpellPricePageDTO;
import com.cnswhy.cloud.server.core.dto.SpellPriceSaveDTO;
import com.cnswhy.cloud.server.core.dto.SpellPriceUpdateDTO;
import com.cnswhy.cloud.server.core.entity.ShopBrand;
import com.cnswhy.cloud.server.core.entity.SpellOrder;
import com.cnswhy.cloud.server.core.entity.SpellPrice;
import com.cnswhy.cloud.server.core.service.spell.SpellOrderService;
import com.cnswhy.cloud.server.core.service.spell.SpellPriceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import com.github.zuihou.security.annotation.PreAuth;


/**
 * <p>
 * 前端控制器
 * 
 * </p>
 *
 * @author cnswhy
 * @date 2020-10-16
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/spellPrice")
@Api(value = "SpellPrice", tags = "")
//@PreAuth(replace = "spellPrice:")
public class SpellPriceController extends SuperController<SpellPriceService, Long, SpellPrice, SpellPricePageDTO, SpellPriceSaveDTO, SpellPriceUpdateDTO> {
    @Autowired
    MessageService messageService;
    @Autowired
    SpellOrderService spellOrderService;
    @Autowired
    IdGeneratorService idGeneratorService;

    @Override
    public R<SpellPrice> handlerSave(SpellPriceSaveDTO model) {
        model.setNewSpellOrderId(idGeneratorService.genCommonIdString());
        return R.successDef();
    }

    @GetMapping("/reset")
    public R<Boolean> getUserRouters() {
        SpellDayendCancelMsg spellDayendCancelMsg = SpellDayendCancelMsg.builder().settDate(SystemClockUtil.getSettDateyyyyMMdd()).build();
        spellDayendCancelMsg.setTraceId(MDCUtil.getTraceId());
        messageService.sendQueueByObject(AmqpExchange.RESET_SPELL_PRICE_MESSAGE,spellDayendCancelMsg);

        return R.success(null);
    }

    @ApiOperation(value = "修改")
    @PutMapping
    @Override
    //@SysLog(value = "'修改:' + #updateDTO?.id", request = false)
    //@PreAuth("hasPermit('{}update')")
    public R<SpellPrice> update(@RequestBody SpellPriceUpdateDTO updateDTO) {
        R<SpellPrice> result = handlerUpdate(updateDTO);
        if (result.getDefExec()) {
            SpellPrice model = BeanUtil.toBean(updateDTO, getEntityClass());
            model.setNewSpellOrderId(null);
            getBaseService().updateById(model);
            model = getBaseService().getById(model.getId());
            if(model.getNewSpellOrderId() == null){
                //新开专区
                model.setNewSpellOrderId(idGeneratorService.genCommonIdString());
                 getBaseService().updateById(model);
                List<SpellOrder> spellOrders = spellOrderService.list(Wraps.<SpellOrder>lbQ().eq(SpellOrder::getPriceId, model.getId()));
                for(SpellOrder spellOrder : spellOrders){
                    spellOrder.setSpellOrderId(model.getNewSpellOrderId());
                }
                spellOrderService.updateBatchById(spellOrders);
            }
            result.setData(model);
            //刷新成团，消息模式
            List<SpellOrder> spellOrders = spellOrderService.getSpellingOrder(model.getNewSpellOrderId(),2);
            if(spellOrders.size() > 0){
                SpellMsg spellMsg = SpellMsg.builder().id(spellOrders.get(0).getId()).build();
                spellMsg.setTraceId(MDCUtil.getTraceId());
                messageService.sendQueueByObject(AmqpExchange.SPELL_MESSAGE,spellMsg);
            }
        }
        return result;
    }

    @Override
    public QueryWrap<SpellPrice> handlerWrapper(SpellPrice model, PageParams<SpellPricePageDTO> params) {
        QueryWrap<SpellPrice> wrapper = model == null ? Wraps.q() : Wraps.q(model);

        if (CollUtil.isNotEmpty(params.getMap())) {
            Map<String, String> map = params.getMap();
            //拼装区间
            for (Map.Entry<String, String> field : map.entrySet()) {
                String key = field.getKey();
                String value = field.getValue();
                if (StrUtil.isEmpty(value)) {
                    continue;
                }
                if (key.endsWith("_st")) {
                    String beanField = StrUtil.subBefore(key, "_st", true);
                    wrapper.ge(getDbField(beanField, getEntityClass()), DateUtils.getStartTime(value));
                }
                if (key.endsWith("_ed")) {
                    String beanField = StrUtil.subBefore(key, "_ed", true);
                    wrapper.le(getDbField(beanField, getEntityClass()), DateUtils.getEndTime(value));
                }
            }
        }
        wrapper.orderByAsc("sort_order");
        return wrapper;
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<SpellPrice> spellPriceList = list.stream().map((map) -> {
            SpellPrice spellPrice = SpellPrice.builder().build();
            return spellPrice;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(spellPriceList));
    }
}
